package com.winit.project.util;

import com.winit.common.util.Constants;
import com.winit.jumpServer.util.JumpServerListInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by wangjian on 16/10/8.
 */
public class ProjectPushUtil {

    private static final Logger logger = LoggerFactory.getLogger(ProjectPushUtil.class);

    /**
     * 生成推送包
     *
     * @return
     */
    public static boolean createPushPackage(String projectName, String editionPath) {
        logger.info("生成推送压缩包,editionPath=" + editionPath);
        List<String> list = JumpServerListInfo.pushTaskList.get(projectName);
        if (list != null && list.size() > 1) {
            File file = new File(editionPath + "/push.tgz");
            if (file.exists()) {
                logger.info("com.winit.project.util.ProjectPushUtil.createPushPackage 多线程推送，包已存在 editionPath=" + editionPath);
                return true;
            }
        }

        String[] param = new String[3];
        param[0] = "bash";
        param[1] = Constants.SHELL_PATH + "shell/build/beetle_create_push_package.sh";
        param[2] = editionPath;
        boolean flag = runSH(param);
        if (!flag) {
            logger.info("生成推送压缩包失败,editionPath=" + editionPath);
        }
        return flag;
    }

    public static boolean delPushPackage(String projectName, String editionPath) {
        logger.info("删除推送压缩包,editionPath=" + editionPath);
        List<String> list = JumpServerListInfo.pushTaskList.get(projectName);
        if (list != null && list.size() > 1) {
            logger.info("com.winit.project.util.ProjectPushUtil.delPushPackage 多线程推送中，不删除包 editionPath=" + editionPath);
            return true;
        }

        String[] param = new String[3];
        param[0] = "bash";
        param[1] = Constants.SHELL_PATH + "shell/build/beetle_del_push_package.sh";
        param[2] = editionPath;
        boolean flag = runSH(param);
        if (!flag) {
            logger.info("删除推送压缩包失败,editionPath=" + editionPath);
        }
        return flag;
    }

    private static boolean runSH(String[] params) {
        boolean flag = false;
        try {
            Process process = Runtime.getRuntime().exec(params);
            BufferedInputStream in = new BufferedInputStream(process.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                logger.info("执行脚本，result=" + line);
                if ("success".equals(line)) {
                    flag = true;
                }
            }
            br.close();
            in.close();
            process.destroy();
        } catch (Exception e) {
            logger.error("执行脚本异常,e:" + e.getMessage());
        }
        return flag;
    }
}
